package com.example.module_android_demo;

//import java.io.File;
//import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.BRMicro.SerialPort;
import com.function.SPconfig;
import com.handheld.uhfdemo3.R;
import com.pow.api.cls.RfidPower;
import com.pow.api.cls.RfidPower.PDATYPE;
import com.uhf.api.cls.Reader;
import com.uhf.api.cls.Reader.AntPower;
import com.uhf.api.cls.Reader.AntPowerConf;
import com.uhf.api.cls.Reader.EmbededData_ST;
import com.uhf.api.cls.Reader.HardwareDetails;
import com.uhf.api.cls.Reader.HoptableData_ST;
import com.uhf.api.cls.Reader.Inv_Potl;
import com.uhf.api.cls.Reader.Inv_Potls_ST;
import com.uhf.api.cls.Reader.Mtr_Param;
import com.uhf.api.cls.Reader.READER_ERR;
import com.uhf.api.cls.Reader.Region_Conf;
import com.uhf.api.cls.Reader.SL_TagProtocol;
import com.uhf.api.cls.Reader.TagFilter_ST;

public class Sub1TabActivity<OpeListActivity> extends Activity {

	private Button button_connect,button_disconnect;
	TabHost tabHost_connect;
	 
	private Spinner spinner_pdatype,spinner_antports;
	@SuppressWarnings("rawtypes")
	private ArrayAdapter /*arradp_pdatype,*/arradp_antports;
	
//	String[] pdatypev={"无","CW","trinea","alps-konka77_cu_ics",
//			"alps-kt45","hd508","IDAT","JIEB","ekemp","alps-konka77_cu_ics_test",
//			"senter-st308w", "senter-st907","alps-g86","HANDH","armor","CZ8800","XISI","XIBA","SENTER907PDA","alps-kt45Q"}; 
	String[] pdaatpot={"一天线","双天线","三天线","四天线"}; 
	String[] baudrate={"9600","19200","38400","57600","115200"};
	 
	MyApplication myapp;

	 /*
	 protected void dialog() {
		  AlertDialog.Builder builder= new Builder(Sub1TabActivity.this);
		  builder.setMessage("确认退出吗？");
		  builder.setTitle("提示"); 
		  builder.setPositiveButton("确认", new OnClickListener(){
			  @Override
			 public void onClick(DialogInterface dialog, int which)
			  {
				  dialog.dismiss();
				  Sub1TabActivity.this.finish();
				  }
			  });
		  builder.setNegativeButton("取消", new OnClickListener(){
			  @Override
			  public void onClick(DialogInterface dialog, int which){
				  dialog.dismiss();
				  }
			  }); 
		   builder.create().show();
		   }
	 */
	 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab1_tablelayout_connect);
		
		Application app=getApplication();
		myapp=(MyApplication) app; 
		myapp.Mreader=new Reader();

		myapp.spf=new SPconfig(this);
		
		
		/*
		// 获取TabHost对象          
				 // 得到TabActivity中的TabHost对象
		tabHost_connect = (TabHost) findViewById(R.id.tabhost1); 
		        
				// 如果没有继承TabActivity时，通过该种方法加载启动tabHost 
		tabHost_connect.setup(); 
			  
		tabHost_connect.getTabWidget().setOrientation(LinearLayout.VERTICAL);
				//tabHost2.addTab(tabHost2.newTabSpec("tab1").setIndicator("初始化",  
				//getResources().getDrawable(R.drawable.ic_launcher)).setContent(R.id.tab11)); 
				 
			    //tabHost2.addTab(tabHost2.newTabSpec("tab1").setIndicator(createIndicatorView(this, tabHost2, "1111"))
			    	//	.setContent(R.id.tab11)); 
		tabHost_connect.addTab(tabHost_connect.newTabSpec("tab1").setIndicator(createIndicatorView(this, tabHost_connect, "连接"))
						.setContent(R.id.tab1_sub_connect)); 
		tabHost_connect.addTab(tabHost_connect.newTabSpec("tab2").setIndicator(createIndicatorView(this, tabHost_connect, "调试")) 
						.setContent(R.id.tab1_sub_debug)); 
		
		TabWidget tw=tabHost_connect.getTabWidget();
		tw.getChildAt(0).setBackgroundColor(Color.BLUE);
		*/
		
			//	View layout = getLayoutInflater().inflate(R.layout.tab1_tablelayout_power, null);
			//	spinner_pdatype= (Spinner)layout.findViewById(R.id.spinner_pdatype);
				 
				spinner_antports = (Spinner) findViewById(R.id.spinner_antports);       	 
				arradp_antports = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,pdaatpot); 
				arradp_antports.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
				spinner_antports.setAdapter(arradp_antports);
				spinner_pdatype = (Spinner) findViewById(R.id.spinner_pdatype); 
				 //将可选内容与ArrayAdapter连接起来         	 
//				arradp_pdatype = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,pdatypev); 
				 //设置下拉列表的风格       
//				arradp_pdatype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				 //将adapter 添加到spinner中       
//				spinner_pdatype.setAdapter(arradp_pdatype);

				button_connect=(Button)findViewById(R.id.button_connect);
				button_disconnect=(Button)findViewById(R.id.button_disconnect);
				
				   /*
				tabHost_connect.setOnTabChangedListener(new OnTabChangeListener(){

					@Override
					public void onTabChanged(String arg0) {
						// TODO Auto-generated method stub
						int j=tabHost_connect.getCurrentTab();
						TabWidget tabIndicator=tabHost_connect.getTabWidget();
						View vw=tabIndicator.getChildAt(j);
						TextView tv=(TextView) vw.findViewById(R.id.tv_indicator);
						//ColorDrawable colorDrawable= (ColorDrawable) tv.getBackground();//获取背景颜色
						//int cl=colorDrawable.getColor();
						vw.setBackgroundColor(Color.BLUE);
						int tc=tabHost_connect.getTabContentView().getChildCount();
						for(int i=0;i<tc;i++)
						{
							if(i!=j)
							{
								View vw2=tabIndicator.getChildAt(i);
							  vw2.setBackgroundColor(Color.TRANSPARENT);
							}
						}
						 
					}
					
				});
				*/
				
				String pdatypestr=myapp.spf.GetString("PDATYPE");
				String addressstr=myapp.spf.GetString("ADDRESS");
				String antportstr=myapp.spf.GetString("ANTPORT");
				 
				if(!pdatypestr.equals(""))
				{
					spinner_pdatype.setSelection(Integer.valueOf(pdatypestr));
					if(spinner_pdatype.getSelectedItemPosition()==0)
					{
						EditText et1=(EditText)findViewById(R.id.editText_adr);
						et1.setText(addressstr);
					}
				}
				 
				if(!antportstr.equals(""))
				{
					spinner_antports.setSelection(Integer.valueOf(antportstr));
				}
				
				//窗体事件
				button_connect.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						connect();
					}

					
				});
				
				button_disconnect.setOnClickListener(new OnClickListener()
				{

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						
						disconnect();
					}

					
					
				});
	 
				spinner_pdatype.setOnItemSelectedListener(new OnItemSelectedListener()
				{

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
					 
						PDATYPE PT=PDATYPE.valueOf(13);
						myapp.Rpower=new RfidPower(PT);
						if(PT!=PDATYPE.NONE)
						{EditText et1=(EditText)findViewById(R.id.editText_adr);
					    et1.setText(myapp.Rpower.GetDevPath());

						//button_connect.requestFocus();
						//button_connect.requestFocusFromTouch();
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						
					}
					
				});
				InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
				  
				inputMethodManager.hideSoftInputFromWindow(Sub1TabActivity.this.getCurrentFocus().getWindowToken(),  
				  
				InputMethodManager.HIDE_NOT_ALWAYS);
				
				
				

			}
			
	private void connect() {
//		EditText et1=(EditText)findViewById(R.id.editText_adr);
//	    String  ip=et1.getText().toString();
//	    if(ip=="") 
//	    {
//	    	Toast.makeText(Sub1TabActivity.this, "地址没有输入",
//			Toast.LENGTH_SHORT).show();
//	    }
		SerialPort serialPort = new SerialPort();
		serialPort.zigbee_poweron();
	    PDATYPE PT=PDATYPE.valueOf(13);
		myapp.Rpower=new RfidPower(PT);
//	    if(myapp.Rpower==null)
//	    {
//	    	Toast.makeText(Sub1TabActivity.this, "请选择平台",
//					Toast.LENGTH_SHORT).show();
//	    }
	   // PDATYPE pt=myapp.Rpower.GetType();
		boolean blen=myapp.Rpower.PowerUp();
		blen = true;
		
	    /* try {
	    	FileWriter localFileWriterOn = new FileWriter(new File("/proc/gpiocontrol/set_id"));
	    	localFileWriterOn.write("1");
	    	localFileWriterOn.close();
	    } catch (Exception e) { 
	    	e.printStackTrace(); 
	    }
	    */

		Toast.makeText(Sub1TabActivity.this, "上电："+String.valueOf(blen),
					Toast.LENGTH_SHORT).show();
		if(!blen)
		return;

		READER_ERR er=myapp.Mreader.InitReader_Notype("/dev/ttyMT1", spinner_antports.getSelectedItemPosition()+1);
		//READER_ERR er=myapp.Mreader.InitReader(ip, Reader_Type.MODULE_ONE_ANT);
		if(er==READER_ERR.MT_OK_ERR)
		{	
			myapp.needreconnect=false;
			myapp.spf.SaveString("PDATYPE", String.valueOf(13));
			myapp.spf.SaveString("ADDRESS", "/dev/ttyMT1");
			myapp.spf.SaveString("ANTPORT", String.valueOf(spinner_antports.getSelectedItemPosition()));
			 
			Toast.makeText(Sub1TabActivity.this, "连接成功",
			Toast.LENGTH_SHORT).show();
			myapp.antportc=spinner_antports.getSelectedItemPosition()+1;  
			ConnectHandleUI();
			myapp.Address="/dev/ttyMT1";
			
		}
			else
			Toast.makeText(Sub1TabActivity.this, "连接失败:"+
			er.toString(),Toast.LENGTH_SHORT).show();
	}
	private void disconnect() {
		// TODO Auto-generated method stub
		if(myapp.Mreader!=null)
			myapp.Mreader.CloseReader();
			boolean blen=myapp.Rpower.PowerDown();
			blen = true;
			SerialPort serialPort = new SerialPort();
			serialPort.zigbeepoweroff();
			/*try {
				FileWriter localFileWriterOff = new FileWriter(new File("/proc/gpiocontrol/set_id"));
				localFileWriterOff.write("0");
				localFileWriterOff.close();
			} catch (Exception e) {
				e.printStackTrace(); 
			}
			 */
			Toast.makeText(Sub1TabActivity.this, "断开读写器，下电："+String.valueOf(blen),
					Toast.LENGTH_SHORT).show();
			DisConnectHandleUI();
	}
	private void ConnectHandleUI()
	{
		try
		{
			READER_ERR er;
			myapp.Rparams=myapp.spf.ReadReaderParams();
			
			 if(myapp.Rparams.invpro.size()<1)
				 myapp.Rparams.invpro.add("GEN2");
		   
		    	 List<SL_TagProtocol> ltp=new ArrayList<SL_TagProtocol>();
				   for(int i=0;i<myapp.Rparams.invpro.size();i++)
				   {  if(myapp.Rparams.invpro.get(i).equals("GEN2"))
				    	{ ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_GEN2);
				    	 
				    	}
				   else if(myapp.Rparams.invpro.get(i).equals("6B"))
				    	{
				    	  ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_ISO180006B);
				    	 
				    	}
				   else if(myapp.Rparams.invpro.get(i).equals("IPX64"))
				    	{
				    	   ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_IPX64);
				    	   
				    	}
				   else if(myapp.Rparams.invpro.get(i).equals("IPX256"))
				    	{
				    	  ltp.add(SL_TagProtocol.SL_TAG_PROTOCOL_IPX256);
				    	  
				    	}
				   }
				     
					Inv_Potls_ST ipst=myapp.Mreader.new Inv_Potls_ST();
					ipst.potlcnt=ltp.size();
					ipst.potls=new Inv_Potl[ipst.potlcnt];
					SL_TagProtocol[] stp=ltp.toArray(new SL_TagProtocol[ipst.potlcnt]);
					for(int i=0;i<ipst.potlcnt;i++)
					{
						Inv_Potl ipl=myapp.Mreader.new Inv_Potl();
						ipl.weight=30;
						ipl.potl=stp[i];
						ipst.potls[0]=ipl;
					}
					
				  er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_INVPOTL, ipst);
			      Log.d("MYINFO", "Connected set pro:"+er.toString());
	 
			 er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_READER_IS_CHK_ANT,
					 new int[]{myapp.Rparams.checkant});
			 Log.d("MYINFO", "Connected set checkant:"+er.toString());
			 
				
			 AntPowerConf apcf=myapp.Mreader.new AntPowerConf();
				apcf.antcnt=myapp.antportc;
				for(int i=0;i<apcf.antcnt;i++)
				{
					AntPower jaap=myapp.Mreader.new AntPower();
					jaap.antid=i+1;
					jaap.readPower =(short)myapp.Rparams.rpow[i];
					jaap.writePower=(short)myapp.Rparams.wpow[i];
					apcf.Powers[i]=jaap; 
				}
				
			myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_RF_ANTPOWER, apcf);
			 
			Region_Conf rre;
			 switch(myapp.Rparams.region)
			 {
			 case 0:
				 rre =Region_Conf.RG_PRC;
				 break;
			 case 1:
				 rre = Region_Conf.RG_NA;
				 break;
			 case 2:
				 rre=Region_Conf.RG_NONE;
				 break;
			 case 3:
				 rre=Region_Conf.RG_KR;
				 break;
			 case 4:
				 rre=Region_Conf.RG_EU;
				 break;
			 case 5:
			 case 6:
			 case 7:
			 case 8:
			 default:
				 rre=Region_Conf.RG_NONE;
				 break;
			 }
			 if(rre!=Region_Conf.RG_NONE)
			 {
				 er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_FREQUENCY_REGION,rre);
			 }
  
			if(myapp.Rparams.frelen>0)
			{
				 
					HoptableData_ST hdst=myapp.Mreader.new HoptableData_ST();
					hdst.lenhtb=myapp.Rparams.frelen;
					hdst.htb=myapp.Rparams.frecys;
					  er=myapp.Mreader.ParamSet
							(Mtr_Param.MTR_PARAM_FREQUENCY_HOPTABLE,hdst);
			}
			 
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_SESSION,
							new int[]{myapp.Rparams.session});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_Q,
					new int[]{myapp.Rparams.qv});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_WRITEMODE,
					new int[]{myapp.Rparams.wmode});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_MAXEPCLEN,
					new int[]{myapp.Rparams.maxlen});
			er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_POTL_GEN2_TARGET,
					new int[]{myapp.Rparams.target});
			 
			if(myapp.Rparams.filenable==1)
			{
				 TagFilter_ST tfst=myapp.Mreader.new TagFilter_ST();
				 tfst.bank=myapp.Rparams.filbank;
				 tfst.fdata=new byte[myapp.Rparams.fildata.length()/2];
				 myapp.Mreader.Str2Hex(myapp.Rparams.fildata,
						 myapp.Rparams.fildata.length(), tfst.fdata);
				 tfst.flen=tfst.fdata.length*8;
				 tfst.startaddr=myapp.Rparams.filadr;
				 tfst.isInvert=myapp.Rparams.filisinver;
		       
				 myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_FILTER, tfst);
			}
		 
			if(myapp.Rparams.emdenable==1)
			{
				EmbededData_ST edst = myapp.Mreader.new EmbededData_ST();
				 
				edst.accesspwd=null;
				edst.bank=myapp.Rparams.emdbank;
				edst.startaddr=myapp.Rparams.emdadr;
				edst.bytecnt=myapp.Rparams.emdbytec;
				edst.accesspwd=null;
			 
				er=myapp.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_EMBEDEDDATA,
						edst);
			}
			 
			er=myapp.Mreader.ParamSet
					(Mtr_Param.MTR_PARAM_TAGDATA_UNIQUEBYEMDDATA,
							new int[]{myapp.Rparams.adataq});
			er=myapp.Mreader.ParamSet
					(Mtr_Param.MTR_PARAM_TAGDATA_RECORDHIGHESTRSSI, 
							new int[]{myapp.Rparams.rhssi});
			er=myapp.Mreader.ParamSet
					(Mtr_Param.MTR_PARAM_TAG_SEARCH_MODE, 
							new int[]{myapp.Rparams.invw});
			
			TextView tv_module=(TextView)findViewById(R.id.textView_module);
			TextView tv_tempurte=(TextView)findViewById(R.id.textView_tempture);
			HardwareDetails val=myapp.Mreader.new HardwareDetails();
			er=myapp.Mreader.GetHardwareDetails(val);
			if(er==READER_ERR.MT_OK_ERR)
			{
				tv_module.setText(val.module.toString());
			}
		 
		}catch(Exception ex)
		{
			Log.d("MYINFO", ex.getMessage()+ex.toString()+ex.getStackTrace());
		}
		 this.button_connect.setEnabled(false);
	        this.button_disconnect.setEnabled(true);
	        TabWidget tw=myapp.tabHost.getTabWidget();
			 tw.getChildAt(1).setVisibility(View.VISIBLE);
			 tw.getChildAt(2).setVisibility(View.VISIBLE);
			 tw.getChildAt(3).setVisibility(View.VISIBLE);
			 myapp.tabHost.setCurrentTab(1);
	}
	private void DisConnectHandleUI()
	{
		button_disconnect.setEnabled(false);
		button_connect.setEnabled(true);
		 TabWidget tw=myapp.tabHost.getTabWidget();
		 tw.getChildAt(1).setVisibility(View.INVISIBLE);
		 tw.getChildAt(2).setVisibility(View.INVISIBLE);
		 tw.getChildAt(3).setVisibility(View.INVISIBLE);
		 TextView tv_module=(TextView)findViewById(R.id.textView_module);
		 tv_module.setText("");
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
	        if((System.currentTimeMillis()-myapp.exittime) > 2000){  
	            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();                                
	            myapp.exittime = System.currentTimeMillis();   
	        } else {
	            finish();
	           // System.exit(0);
	        }
	        return true;   
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
}
